﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Collections.Specialized;
using System.Net.Sockets;
using System.Net;
using System.Threading;

////////////
/// 
/// Duplicated to System.Net.Mail
/// By marstone@marstone.net, 2008/12/02
/// 
////////////
namespace Studio.Network.MailServer
{

    public class SmtpCommand
    {
        SmtpVerbs _verb;

        public SmtpVerbs Verb
        {
            get { return _verb; }
            set { _verb = value; }
        }

        string _commandString;

        public string CommandString
        {
            get { return _commandString; }
            set { _commandString = value; }
        }

        public SmtpCommand(string command)
        {
            this.ParseCommand(command);
        }

        string _data = string.Empty;

        public string Data
        {
            get { return _data; }
            set { _data = value; }
        }

        /// <summary>
        /// Mapping from SmtpVerb to its Prefix
        /// </summary>
        public static readonly Dictionary<SmtpVerbs, string> VERB_DICTIONARY = new Dictionary<SmtpVerbs, string>() 
        { 
            {SmtpVerbs.DATA, "DATA"},
            {SmtpVerbs.HELO, "HELO"},
            {SmtpVerbs.MAIL, "MAIL FROM:"},
            {SmtpVerbs.RCPT, "RCPT TO:"},
            {SmtpVerbs.QUIT, "QUIT"}
        };

        void ParseCommand(string command)
        {
            this._commandString = command;
            this._verb = SmtpVerbs.NONE;
            foreach (SmtpVerbs verb in VERB_DICTIONARY.Keys)
            {
                string prefix = VERB_DICTIONARY[verb];
                if (true == command.ToUpper().StartsWith(prefix))
                {
                    this._verb = verb;
                    this._data = command.Substring(prefix.Length).Trim(" <>\r\n\t\"".ToCharArray());
                    break;
                }
            }
        }

        public static SmtpCommand Parse(string command)
        {
            return new SmtpCommand(command);
        }
    }
}
